const express = require("express");
const router = express.Router();
const sqlClient = require("./mysql");
// 图片所需要的模块  multer安装
const multer = require("multer");
var fs = require("fs");
// const { config } = require("process");
const jwt = require("jsonwebtoken");
const config = require("./secert");
const Mock = require("mockjs");
// 路由接口

/**
 * 注册
 */
router.post("/register", (req, res) => {
  const { username, password } = req.body;
  const sql = "insert into user values(null,?,?)";
  const arr = [username, password];
  sqlClient(sql, arr, result => {
    if (result.affectedRows > 0) {
      res.send({
        status: 200,
        msg: "注册成功",
      });
    } else {
      res.send({
        status: 401,
        msg: "注册失败",
      });
    }
  });
});

/**
 * 登陆
 */
router.post("/login", (req, res) => {
  const { username, password } = req.body;
  const sql = "select * from user where username=? and password=?";
  const arr = [username, password];
  sqlClient(sql, arr, result => {
    if (result.length > 0) {
      let token = jwt.sign(
        {
          username: result[0].username,
          id: result[0].id,
        },
        config.jwtSecret,
        {
          expiresIn: 20 * 1,
        }
      );
      res.send({
        status: 200,
        data: token,
      });
    } else {
      res.send({
        status: 401,
        msg: "登陆失败",
      });
    }
  });
});

// 商品列表
router.get("/projectList", (req, res) => {
  // 分页
  const page = req.query.page || 1;
  // const sql = "select * from project order by id desc limit 10 offset " + (page - 1) * 10;
  const sqlLen = "select * from project where id";
  sqlClient(sqlLen, null, data => {
    len = data.length;
    const sql =
      "select * from project order by id desc limit 8 offset " + (page - 1) * 8;
    sqlClient(sql, null, result => {
      if (result.length > 0) {
        res.send({
          status: 200,
          data: result,
          pageSize: 8,
          total: len,
        });
      } else {
        res.send({
          status: 500,
          msg: "暂无数据",
        });
      }
    });
  });
});

// 商品查询
router.get("/search", (req, res) => {
  const search = req.query.search;
  const sql =
    "select * from project where concat(`title`,`sellPoint`,`descs`) like '%" +
    search +
    "%'";
  sqlClient(sql, null, result => {
    if (result.length > 0) {
      res.send({
        status: 200,
        result,
      });
    } else {
      res.send({
        status: 500,
        msg: "暂无数据",
      });
    }
  });
});

/**
 * 类目选择
 */
router.get("/backend/itemCategory/selectItemCategoryByParentId", (req, res) => {
  const id = req.query.id || 1;
  const sql = "select * from category where id=?";
  const arr = [id];
  sqlClient(sql, arr, result => {
    if (result.length > 0) {
      res.send({
        status: 200,
        result,
      });
    } else {
      res.send({
        status: 500,
        msg: "暂无数据",
      });
    }
  });
});

// 类目结构获取
router.get("/category/data", (req, res) => {
  var cid = req.query.cid;
  var sql = "select * from params where itemCatId=?";
  sqlClient(sql, [cid], result => {
    if (result.length > 0) {
      res.send({
        status: 200,
        result,
      });
    } else {
      res.send({
        status: 500,
        msg: "暂无数据",
      });
    }
  });
});

// 图片上传
/**
 * 上传图片
 */
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./upload/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

var createFolder = function (folder) {
  try {
    fs.accessSync(folder);
  } catch (e) {
    fs.mkdirSync(folder);
  }
};

var uploadFolder = "./upload/";
createFolder(uploadFolder);
var upload = multer({ storage: storage });

router.post("/upload", upload.single("file"), function (req, res, next) {
  var file = req.file;
  console.log("文件类型：%s", file.mimetype);
  console.log("原始文件名：%s", file.originalname);
  console.log("文件大小：%s", file.size);
  console.log("文件保存路径：%s", file.path);
  res.json({ res_code: "0", name: file.originalname, url: file.path });
});

/**
 * 添加商品
 */
router.get("/backend/item/insertTbItem", (req, res) => {
  var title = req.query.title || "";
  var cid = req.query.cid || "";
  
  var category = req.query.category || "";
  var sellPoint = req.query.sellPoint || "";
  var price = req.query.price || "";
  var num = req.query.num || "";
  var image = req.query.image || "";
  var desc = req.query.descs || "";
  var paramsInfo = req.query.paramsInfo || "";
  const sql = "insert into project values (null,?,?,?,?,?,?,'',1,'','',?,?,?)";
  // cid,title,price,num,sellPoint,image,descs,category
  var arr = [title, image, sellPoint, price, cid, num, desc, category,paramsInfo];
  sqlClient(sql, arr, result => {
    if (result.affectedRows > 0) {
      res.send({
        status: 200,
        msg: "添加成功",
      });
    } else {
      res.send({
        status: 500,
        msg: "添加失败",
      });
    }
  });
});

/**
 * 商品删除
 */
router.get("/backend/item/deleteItemById", (req, res) => {
  const id = req.query.id;
  const sql = "delete from project where id=?";
  const arr = [id];
  sqlClient(sql, arr, result => {
    if (result.affectedRows > 0) {
      res.send({
        status: 200,
        msg: "删除成功",
      });
    } else {
      res.send({
        status: 500,
        msg: "删除失败",
      });
    }
  });
});

/**
 *
 * 批量删除
 **/
router.get("/batchDelete", (req, res) => {
  let arr = req.query.id;
  let sql = "";
  function fun(arr) {
    sql = `delete from project where id in (`;
    for (let i = 0; i < arr.length; i++) {
      sql += arr[i] + ",";
    }
    sql = sql.slice(0, -1);
    sql = sql + ")";
  }
  fun(arr);
  sqlClient(sql, null, result => {
    if (result.affectedRows > 0) {
      res.send({
        status: 200,
        msg: "删除成功",
      });
    } else {
      res.send({
        status: 500,
        msg: "删除失败",
      });
    }
  });
});
// 修改商品
router.get("/backend/item/updateTbItem", (req, res) => {
  var id = req.query.id;
  var title = req.query.title || "";
  var sellPoint = req.query.sellPoint || "";
  var price = req.query.price || "";
  var cid = req.query.cid || "";
  var category = req.query.category || "";
  var num = req.query.num || "";
  var desc = req.query.descs || "";
  var image = req.query.image || "";
  const sql =
    "update project set title=?,sellPoint=?,price=?,cid=?,category=?,num=?,descs=?,image=? where id=?";
  var arr = [title, sellPoint, price, cid, category, num, desc, image, id];

  sqlClient(sql, arr, result => {
    if (result.affectedRows > 0) {
      res.send({
        status: 200,
        msg: "修改成功",
      });
    } else {
      res.send({
        status: 500,
        msg: "修改失败",
      });
    }
  });
});

router.get("/mock", (req, res) => {
  let data = Mock.mock({
    info: "我是个单纯的对象",
    "list|6": [{}],
  });
  res.send(data);
});

/**
 * 规格参数查询
 */
router.get("/backend/itemParam/selectItemParamAll", (req, res) => {
  const page = req.query.page || 1;
  const sqlLen = "select * from params where id";
  const sql =
    "select * from params order by id desc limit 8 offset " + (page - 1) * 8;
  sqlClient(sqlLen, null, data => {
    len = data.length;

    sqlClient(sql, null, result => {
      if (result.length > 0) {
        res.send({
          status: 200,
          result,
          total: len,
          pageSize: 8,
        });
      } else {
        res.send({
          status: 500,
          msg: "查询失败",
        });
      }
    });
  });
});

/**
 * 规格参数模糊查询
 */
router.get("/params/search", (req, res) => {
  const search = req.query.search;
  const sql =
    "select * from params where concat(`paramData`) like '%" + search + "%'";
  sqlClient(sql, [search], result => {
    if (result.length > 0) {
      res.send({
        status: 200,
        result,
      });
    } else {
      res.send({
        status: 500,
        msg: "暂无数据",
      });
    }
  });
});
// 添加规格参数
router.get("/backend/itemParam/insertItemParam", (req, res) => {
  var itemCatId = req.query.itemCatId;
  var paramsContent = req.query.content;
  var specsName = req.query.specsName;
  var sql = "insert into params values (null,?,?,?)";

  sqlClient(sql, [itemCatId, paramsContent, specsName], result => {
    if (result.affectedRows > 0) {
      res.send({
        status: 200,
        msg: "添加成功",
      });
    } else {
      res.send({
        status: 500,
        msg: "添加失败",
      });
    }
  });
});



// // 修改规格参数
// router.get("/update/category", (req, res) => {
//   var cid = req.query.cid;
//   var content = req.query.content;
//   var id = req.query.id;
//   var specsName = req.query.specsName;
//   var sql = "update params set paramData=?,itemCatId=?,specsName=? where id=?";
//   sqlClient(sql, [content, cid, specsName, id], result => {
//     if (result.affectedRows > 0) {
//       res.send({
//         status: 200,
//         msg: "修改成功",
//       });
//     } else {
//       res.send({
//         status: 500,
//         msg: "修改失败",
//       });
//     }
//   });
// });

// // 删除规格参数
// router.get("/params/delete", (req, res) => {
//   var id = req.query.id;
//   var sql = "delete from params where id=?";
//   const arr = [id];
//   sqlClient(sql, arr, result => {
//     if (result.affectedRows > 0) {
//       res.send({
//         status: 200,
//         msg: "删除成功",
//       });
//     } else {
//       res.send({
//         status: 500,
//         msg: "删除失败",
//       });
//     }
//   });
// });


// 
module.exports = router;
